import { Setting } from '../models';
import { getSettingsFromRedis, updateSettingsFromRedis } from '../bin/init';

export default function (router) {
  /**
   * 小程序获取配置项接口
   */
  router.get('/api/front/settings', async ctx => {
    const settings = await getSettingsFromRedis();
    await ctx.json(true, 'success', settings || {});
  });

  /**
   * 后台获取所有的设置项
   */
  router.get('/api/admin/setting', async ctx => {
    const { keyword } = ctx.request.query;
    let condition = {};
    if (keyword) {
      condition.$or = [{ name: new RegExp(keyword, 'i') }, { key: new RegExp(keyword, 'i') }];
    }
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);
    const total = await Setting.countDocuments(condition);
    const settings = await Setting.find(condition)
      .skip((page - 1) * limit)
      .limit(limit);
    await ctx.json(true, 'success', { list: settings, total });
  });

  /**
   * 后台修改设置项
   */
  router.put('/api/admin/setting/:id', async ctx => {
    const id = ctx.params.id;
    const { key, value, name, des } = ctx.request.body;
    if (!id) {
      await ctx.json(false, '参数错误');
      return false;
    }
    const thisSetting = await Setting.findById(id, '_id');
    if (!thisSetting) {
      await ctx.json(false, '找不到该设置');
      return false;
    }
    const updateResult = await Setting.updateOne(
      { _id: id },
      {
        $set: {
          key,
          value,
          name,
          des
        }
      }
    );
    if (updateResult.ok) {
      await updateSettingsFromRedis();
      await ctx.json(true, '更新设置成功');
    } else {
      await ctx.json(false, '更新设置失败');
    }
  });

  /**
   * 后台新增设置项
   */
  router.post('/api/admin/setting', async ctx => {
    const { key, value, name, des } = ctx.request.body;
    if (!key) {
      await ctx.json(false, '参数错误');
      return false;
    }
    const newSetting = await Setting.create({
      // @ts-ignore
      key,
      value,
      name,
      des,
      create_time: Date.now()
    });

    if (newSetting) {
      await updateSettingsFromRedis();
      await ctx.json(true, '新增设置成功');
    } else {
      await ctx.json(false, '新增设置失败');
    }
  });

  /**
   * 后台删除设置项
   */
  router.delete('/api/admin/setting/:id', async ctx => {
    const id = ctx.params.id;
    if (!id) {
      await ctx.json(false, '参数错误');
      return false;
    }
    const thisSetting = await Setting.findById(id, '_id');
    if (!thisSetting) {
      await ctx.json(false, '找不到该设置');
      return false;
    }
    const deleteResult = await Setting.deleteOne({ _id: id });
    if (deleteResult.ok) {
      await updateSettingsFromRedis();
      await ctx.json(true, '删除设置成功');
    } else {
      await ctx.json(false, '删除设置失败');
    }
  });
}
